// Activating the ADC interrupts
void Analog_Init(void)
{
  // Set prescaler to 32, so ADC clock is now 500 KHz
  // bitSet(ADCSRA, ADPS2);
  // bitClear(ADCSRA, ADPS1);
  // bitSet(ADCSRA, ADPS0);

  ADCSRA|=(1<<ADIE)|(1<<ADEN); // Enable interrupt and enable ADC
  ADMUX = (DEFAULT << 6);  // Select channel 0

  ADCSRA|= (1<<ADSC);  // Start the conversion
}

//ADC interrupt
ISR(ADC_vect)
{
  volatile uint8_t low, high;
  low = ADCL;
  high = ADCH;

  adc_old = adc_new;
  adc_new = (high << 8) | low;

  if (adc_new > 150){
    adc_raw += adc_new;
    adc_count++;
  }

  //rising edge detection
  if (adc_old == 0 && adc_new  > 0)
  {
    tt = micros();
    if (count_rising == 0)
    {
      ttold = tt;
    }
    count_rising++;

    if (tt - ttold > SAMPLING_TIME)
    {
      count_rising--;

      freq = (1000000 * count_rising) / (tt - ttold);
      motor_speed = freq * 120  / POLES;

      Serial.print(motor_speed);
      Serial.print(" ");
      Serial.println(adc_raw/adc_count*VREF/1023.*R_DIVISOR, 3); //voltage on transistor gate
      count_rising = 0;
      ttold = 0;
      tt = 0;
      adc_count = 0;
      adc_raw = 0;
    }
  }

  ADCSRA|= (1<<ADSC);  // Start the conversion
}


